#!/usr/bin/env python
from makefont import create_cairo_font_face_for_file
import cairo, util, collection.manager

class NetBody:
	def __init__(self):
		self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, util.CONST.WIN_WIDTH, util.CONST.WIN_HEIGHT)
		self.out_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, util.CONST.WIN_WIDTH/2, util.CONST.WIN_HEIGHT/2)
		self.ctx = cairo.Context(self.surface)
		self.out_ctx = cairo.Context(self.out_surface)
		self.ctx.set_font_face(create_cairo_font_face_for_file("resources/Inconsolata.otf"))
	
	def draw(self):
		n = 0
		while True:
			try:
				self.ctx.set_source_rgb(0.9, 0.9, 0.8) # clear to black
				self.ctx.paint()

				has_active = False
				esets = collection.manager.entity_list.values()
				if esets:
					combined_entities = reduce(lambda x,y:x+y, esets)
					# draw network first
					for e in combined_entities:
						if not has_active and e.active and not e.next_seed: has_active = True
						e.draw_network(self.ctx)
					# draw entities on top
					for e in combined_entities:
						e.draw(self.ctx)

				if not has_active:
					# active nodes have finished drawing, spider again with seed
					collection.manager.spider()

				if util.CONST.SAVE_FRAMES:
					self.out_ctx.set_source_surface(self.surface, 0, 0)
					self.out_ctx.paint()
					self.out_ctx.scale(0.5, 0.5)
					self.out_surface.write_to_png("output/frame%05d.png" % n)
					self.out_ctx.scale(2.0, 2.0)
					n = n + 1
				# push entities around
				collection.manager.base.posi.force_place()
				util.log('ENDFRAME')
			except KeyboardInterrupt:
				print "ok, done"
				break

if __name__ == '__main__':
	nb = NetBody()
	util.log('INIT')
	nb.draw()
